<template>
<el-dialog
    v-model="visible"
    :title="isEdit ? '编辑住户' : '新增住户'"
    width="600px"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="formRules"
      label-width="100px"
    >
      <el-form-item label="住户姓名" prop="realName">
        <el-input v-model="form.realName" placeholder="请输入住户姓名" />
      </el-form-item>
      
      <el-form-item label="身份证件类型" prop="identityType">
        <el-select v-model="form.identityType" placeholder="请选择身份证件类型" style="width: 100%" @change="handleIdentityTypeChange">
          <el-option label="身份证" :value="1" />
          <el-option label="护照" :value="2" />
          <el-option label="港澳通行证" :value="3" />
          <el-option label="台湾通行证" :value="4" />
        </el-select>
      </el-form-item>
      
      <el-form-item label="身份证件号" prop="identityNo">
        <el-input v-model="form.identityNo" :placeholder="getIdentityNoPlaceholder()" />
      </el-form-item>
      
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="form.phone" placeholder="请输入手机号" />
      </el-form-item>
      
      <el-form-item label="性别" prop="gender">
        <el-radio-group v-model="form.gender">
                        <el-radio :value="1">男</el-radio>
              <el-radio :value="2">女</el-radio>
              <el-radio :value="0">未知</el-radio>
        </el-radio-group>
      </el-form-item>
      
      <el-form-item label="出生日期" prop="birthday">
        <el-date-picker
          v-model="form.birthday"
          type="date"
          placeholder="请选择出生日期"
          style="width: 100%"
        />
      </el-form-item>
      
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="form.email" placeholder="请输入邮箱" />
      </el-form-item>
      
      <el-form-item label="学历" prop="education">
        <el-input v-model="form.education" placeholder="请输入学历" />
      </el-form-item>
      
      <el-form-item label="职业" prop="profession">
        <el-input v-model="form.profession" placeholder="请输入职业" />
      </el-form-item>
      
      <el-form-item label="工作单位" prop="workUnit">
        <el-input v-model="form.workUnit" placeholder="请输入工作单位" />
      </el-form-item>
      
      <el-form-item label="籍贯" prop="nativePlace">
        <el-input v-model="form.nativePlace" placeholder="请输入籍贯" />
      </el-form-item>
      
      <el-form-item label="紧急联系人" prop="emergencyContact">
        <el-input v-model="form.emergencyContact" placeholder="请输入紧急联系人" />
      </el-form-item>
      
      <el-form-item label="紧急联系电话" prop="emergencyPhone">
        <el-input v-model="form.emergencyPhone" placeholder="请输入紧急联系电话" />
      </el-form-item>
      
      <el-form-item label="车辆信息" prop="vehicleInfo">
        <el-input v-model="form.vehicleInfo" placeholder="请输入车辆信息" />
      </el-form-item>
      
      <el-form-item label="宠物信息" prop="petInfo">
        <el-input v-model="form.petInfo" placeholder="请输入宠物信息" />
      </el-form-item>
      
      <el-form-item label="特殊需求" prop="specialNeeds">
        <el-input v-model="form.specialNeeds" placeholder="请输入特殊需求" />
      </el-form-item>
      
      <el-form-item label="住户身份" prop="residentType">
        <el-select v-model="form.residentType" placeholder="请选择住户身份" style="width: 100%">
          <el-option label="户主" :value="1" />
          <el-option label="家庭成员" :value="2" />
          <el-option label="租客" :value="3" />
          <el-option label="临时居住" :value="4" />
        </el-select>
      </el-form-item>
      
      <el-form-item label="入住日期" prop="moveInDate">
        <el-date-picker
          v-model="form.moveInDate"
          type="date"
          placeholder="请选择入住日期"
          style="width: 100%"
        />
      </el-form-item>
      
      <el-form-item label="搬出日期" prop="moveOutDate">
        <el-date-picker
          v-model="form.moveOutDate"
          type="date"
          placeholder="请选择搬出日期"
          style="width: 100%"
        />
      </el-form-item>
      
      <el-form-item label="合同开始日期" prop="contractStartDate" v-if="form.residentType === 3">
        <el-date-picker
          v-model="form.contractStartDate"
          type="date"
          placeholder="请选择合同开始日期"
          style="width: 100%"
        />
      </el-form-item>
      
      <el-form-item label="合同结束日期" prop="contractEndDate" v-if="form.residentType === 3">
        <el-date-picker
          v-model="form.contractEndDate"
          type="date"
          placeholder="请选择合同结束日期"
          style="width: 100%"
        />
      </el-form-item>
      
      <el-form-item label="月租金" prop="monthlyRent" v-if="form.residentType === 3">
        <el-input-number
          v-model="form.monthlyRent"
          :precision="2"
          :step="100"
          :min="0"
          placeholder="请输入月租金"
          style="width: 100%"
        />
      </el-form-item>
      
      <el-form-item label="押金" prop="deposit" v-if="form.residentType === 3">
        <el-input-number
          v-model="form.deposit"
          :precision="2"
          :step="100"
          :min="0"
          placeholder="请输入押金"
          style="width: 100%"
        />
      </el-form-item>
      
      <el-form-item label="合同编号" prop="contractNo" v-if="form.residentType === 3">
        <el-input v-model="form.contractNo" placeholder="请输入合同编号" />
      </el-form-item>
      
      <el-form-item label="住户状态" prop="status">
        <el-select v-model="form.status" placeholder="请选择住户状态" style="width: 100%">
          <el-option label="正常居住" :value="1" />
          <el-option label="暂时外出" :value="2" />
          <el-option label="已搬出" :value="0" />
        </el-select>
      </el-form-item>
      
      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="form.remark"
          type="textarea"
          :rows="3"
          placeholder="请输入备注信息"
        />
      </el-form-item>
    </el-form>
    
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="submitting">
        {{ isEdit ? '更新' : '创建' }}
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
/**
 * 住户表单组件
 * @author Wu.Liang
 * @date 2025-07-28
 */
import { ref, reactive, computed, watch, nextTick } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { residentApi } from '@/api/resident'
import { showMessage } from '@/utils/message'
import { ElMessage } from 'element-plus'
import { useResidentStore } from '@/store/resident'

// 定义props
interface Props {
  visible: boolean
  formData: any
  householdId: number
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  formData: null,
  householdId: 0
})

// 定义emits
const emit = defineEmits<{
  'update:visible': [value: boolean]
  'success': []
}>()

// 响应式数据
const formRef = ref<FormInstance>()
const submitting = ref(false)
const residentStore = useResidentStore()

// 表单数据
const form = reactive({
  realName: '',
  identityType: 1,
  identityNo: '',
  phone: '',
  gender: undefined as number | undefined,
  birthday: undefined as string | undefined,
  email: '',
  education: '',
  profession: '',
  workUnit: '',
  nativePlace: '',
  emergencyContact: '',
  emergencyPhone: '',
        vehicleInfo: '',
      petInfo: '',
      specialNeeds: '',
      status: 1,
      remark: '',
      // 住户房户关联信息
      residentType: 1,
      moveInDate: undefined,
      moveOutDate: undefined,
      contractStartDate: undefined,
      contractEndDate: undefined,
      monthlyRent: undefined,
      deposit: undefined,
      contractNo: ''
})

// 计算属性
const visible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

const isEdit = computed(() => !!props.formData)

// 获取身份证件号输入框提示
const getIdentityNoPlaceholder = () => {
  switch (form.identityType) {
    case 1:
      return '请输入身份证号'
    case 2:
      return '请输入护照号'
    case 3:
      return '请输入港澳通行证号'
    case 4:
      return '请输入台湾通行证号'
    default:
      return '请输入身份证件号'
  }
}

// 身份证件类型变化处理
const handleIdentityTypeChange = () => {
  // 清空身份证件号
  form.identityNo = ''
  // 重新验证
  nextTick(() => {
    formRef.value?.validateField('identityNo')
  })
}

// 表单验证规则
const formRules: FormRules = {
  realName: [
    { required: true, message: '请输入住户姓名', trigger: 'blur' },
    { min: 2, max: 50, message: '住户姓名长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  identityType: [
    { required: true, message: '请选择身份证件类型', trigger: 'change' }
  ],
  identityNo: [
    { required: true, message: '请输入身份证件号', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error('请输入身份证件号'))
          return
        }
        
        // 根据身份证件类型进行不同的验证
        switch (form.identityType) {
          case 1: // 身份证
            if (!/^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/.test(value)) {
              callback(new Error('请输入正确的身份证号'))
            } else {
              callback()
            }
            break
          case 2: // 护照
            if (!/^[a-zA-Z0-9]{5,17}$/.test(value)) {
              callback(new Error('请输入正确的护照号'))
            } else {
              callback()
            }
            break
          case 3: // 港澳通行证
            if (!/^[HMhm]{1}([0-9]{10}|[0-9]{8})$/.test(value)) {
              callback(new Error('请输入正确的港澳通行证号'))
            } else {
              callback()
            }
            break
          case 4: // 台湾通行证
            if (!/^[0-9]{8}$/.test(value)) {
              callback(new Error('请输入正确的台湾通行证号'))
            } else {
              callback()
            }
            break
          default:
            callback()
        }
      },
      trigger: 'blur'
    }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择住户状态', trigger: 'change' }
  ],
  emergencyPhone: [
    { pattern: /^1[3-9]\d{9}$/, message: '紧急联系电话格式不正确', trigger: 'blur' }
  ],
  residentType: [
    { required: true, message: '请选择住户身份', trigger: 'change' }
  ],
  moveInDate: [
    { required: true, message: '请选择入住日期', trigger: 'change' }
  ]
}

// 监听formData变化，初始化表单数据
watch(() => props.formData, (newData) => {
  if (newData) {
    // 编辑模式，填充表单数据
    Object.assign(form, {
      realName: newData.realName || '',
      identityType: newData.identityType || 1,
      identityNo: newData.identityNo || '',
      phone: newData.phone || '',
      gender: newData.gender,
      birthday: newData.birthday,
      email: newData.email || '',
      education: newData.education || '',
      profession: newData.profession || '',
      workUnit: newData.workUnit || '',
      nativePlace: newData.nativePlace || '',
      emergencyContact: newData.emergencyContact || '',
      emergencyPhone: newData.emergencyPhone || '',
      vehicleInfo: newData.vehicleInfo || '',
      petInfo: newData.petInfo || '',
      specialNeeds: newData.specialNeeds || '',
      status: newData.status || 1,
      remark: newData.remark || '',
      // 住户房户关联信息
      residentType: newData.residentType || 1,
      moveInDate: newData.moveInDate,
      moveOutDate: newData.moveOutDate,
      contractStartDate: newData.contractStartDate,
      contractEndDate: newData.contractEndDate,
      monthlyRent: newData.monthlyRent,
      deposit: newData.deposit,
      contractNo: newData.contractNo || ''
    })
    // 延迟清除验证错误，确保数据完全加载后再清除
    nextTick(() => {
      setTimeout(() => {
        formRef.value?.clearValidate()
      }, 100)
    })
  } else {
    // 新增模式，重置表单数据
    Object.assign(form, {
      realName: '',
      identityType: 1,
      identityNo: '',
      phone: '',
      gender: undefined,
      birthday: undefined,
      email: '',
      education: '',
      profession: '',
      workUnit: '',
      nativePlace: '',
      emergencyContact: '',
      emergencyPhone: '',
      vehicleInfo: '',
      petInfo: '',
      specialNeeds: '',
      status: 1,
      remark: ''
    })
  }
}, { immediate: true })

// 关闭弹窗
const handleClose = () => {
  visible.value = false
  formRef.value?.resetFields()
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitting.value = true
    
    // 构建住户基本信息
    const residentData = {
      realName: form.realName,
      identityType: form.identityType,
      identityNo: form.identityNo,
      gender: form.gender,
      birthday: form.birthday,
      phone: form.phone,
      email: form.email,
      education: form.education,
      profession: form.profession,
      workUnit: form.workUnit,
      nativePlace: form.nativePlace,
      emergencyContact: form.emergencyContact,
      emergencyPhone: form.emergencyPhone,
      vehicleInfo: form.vehicleInfo,
      petInfo: form.petInfo,
      specialNeeds: form.specialNeeds,
      status: form.status,
      remark: form.remark,
      householdId: props.householdId,
      // 住户房户关联信息
      residentType: form.residentType,
      moveInDate: form.moveInDate,
      moveOutDate: form.moveOutDate,
      contractStartDate: form.contractStartDate,
      contractEndDate: form.contractEndDate,
      monthlyRent: form.monthlyRent,
      deposit: form.deposit,
      contractNo: form.contractNo
    }
    
    if (props.formData.id) {
      // 编辑 - 更新住户信息
      await residentStore.updateResident(props.formData.id, residentData)
      ElMessage.success('更新成功')
    } else {
      // 新增 - 创建住户信息（后端会自动处理用户关联）
      await residentStore.addResident(residentData)
      ElMessage.success('添加成功')
    }
    
    emit('success')
    handleClose()
  } catch (error: any) {
    console.error('提交失败:', error)
    ElMessage.error('操作失败: ' + (error.message || '未知错误'))
  } finally {
    submitting.value = false
  }
}
</script>

<style scoped>
.el-form-item {
  margin-bottom: 20px;
}
</style> 